package com.itmk.web.menu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itmk.web.menu.entity.Menu;
import com.itmk.web.menu.service.MenuService;
import itmk.utils.ResultUtils;
import itmk.utils.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 树数据列表
     * @return
     */
    @GetMapping("/list")
    public ResultVo list(){
        List<Menu> list = menuService.getList();
        return ResultUtils.success("查询菜单成功！",list);
    }

    /**
     * 新增菜单
     * @param menu
     * @return
     */
    @PostMapping
    public ResultVo addMenu(@RequestBody Menu menu){
        boolean save = menuService.save(menu);
        if (save){
            return ResultUtils.success("新增菜单成功!");
        }
        return ResultUtils.error("新增菜单失败!");
    }

    /**
     * 编辑菜单
     * @param menu
     * @return
     */
    @PutMapping
    public ResultVo editMenu(@RequestBody Menu menu){
        boolean b = menuService.updateById(menu);
        if (b){
            return ResultUtils.success("编辑菜单成功！");
        }
        return ResultUtils.error("编辑菜单失败!");
    }

    /**
     * 删除菜单
     * @param menuId
     * @return
     */
    @DeleteMapping("/{menuId}")
    public  ResultVo deleteMenu(@PathVariable("menuId") Long menuId ){
        //如果该菜单有下级，则不能删除
        QueryWrapper<Menu>query =new QueryWrapper<>();
        query.lambda().eq(Menu::getParentId,menuId);
        List<Menu> list = menuService.list();
        if (list.size()>0){
            return  ResultUtils.error("该菜单有下级，不能删除！");
        }

        boolean b = menuService.removeById(menuId);
        if (b){
            return ResultUtils.success("删除菜单成功！");
        }
        return ResultUtils.error("删除菜单失败！");
    }

    /**
     * 获取上级菜单
     * @return
     */
    @GetMapping("/parent")
    public ResultVo getParent(){
        List<Menu> parentList = menuService.getParentList();
        return ResultUtils.success("查询上级菜单成功！",parentList);
    }
}

